﻿using YDT_SeckillService.Domain.Enums;

namespace YDT_SeckillService.Domain.Entities
{
    /// <summary>
    /// 秒杀活动聚合根 - 秒杀活动是聚合根，包含秒杀商品集合
    /// 聚合根：负责维护秒杀活动的完整性和业务规则
    /// </summary>
    public class Seckill : Entity, IAggregateRoot
    {
        /// <summary>秒杀时间主题URL</summary>
        public string TimeTitleUrl { get; private set; }
        /// <summary>秒杀日期</summary>
        public DateOnly SeckillDate { get; private set; }
        /// <summary>秒杀开始时间</summary>
        public TimeOnly SeckillStartTime { get; private set; }
        /// <summary>秒杀结束时间</summary>
        public TimeOnly SeckillEndTime { get; private set; }
        /// <summary>秒杀时间状态</summary>
        public SeckillTimeStatus TimeStatus { get; private set; }
        /// <summary>创建时间</summary>
        public DateTime CreateTime { get; private set; }
        /// <summary>更新时间</summary>
        public DateTime UpdateTime { get; set; }

        /// <summary>秒杀商品集合 - 私有字段确保通过方法修改</summary>
        private readonly List<SeckillProduct> _seckillProducts = new();
        /// <summary>秒杀商品只读集合</summary>
        public IReadOnlyCollection<SeckillProduct> SeckillProducts => _seckillProducts.AsReadOnly();

        /// <summary>
        /// 受保护的构造函数 - 用于EF Core
        /// </summary>
        protected Seckill() { }

        /// <summary>
        /// 创建秒杀活动构造函数
        /// </summary>
        public Seckill(string timeTitleUrl, DateOnly seckillDate, TimeOnly seckillStartTime,
                      TimeOnly seckillEndTime)
        {
            Id = Guid.NewGuid();
            TimeTitleUrl = timeTitleUrl;
            SeckillDate = seckillDate;
            SeckillStartTime = seckillStartTime;
            SeckillEndTime = seckillEndTime;
            TimeStatus = SeckillTimeStatus.Disabled; // 默认禁用状态
            CreateTime = DateTime.UtcNow;
            UpdateTime = DateTime.UtcNow;

            // 验证业务规则
            ValidateCreation();
        }

        /// <summary>
        /// 更新秒杀活动基本信息
        /// </summary>
        public void UpdateBasicInfo(string timeTitleUrl, DateOnly seckillDate,
                                   TimeOnly seckillStartTime, TimeOnly seckillEndTime)
        {
            TimeTitleUrl = timeTitleUrl;
            SeckillDate = seckillDate;
            SeckillStartTime = seckillStartTime;
            SeckillEndTime = seckillEndTime;
            UpdateTime = DateTime.UtcNow;

            ValidateBasicInfo();
        }

        /// <summary>
        /// 启用秒杀活动
        /// </summary>
        public void Enable()
        {
            TimeStatus = SeckillTimeStatus.Enabled;
            UpdateTime = DateTime.UtcNow;
        }

        /// <summary>
        /// 禁用秒杀活动
        /// </summary>
        public void Disable()
        {
            TimeStatus = SeckillTimeStatus.Disabled;
            UpdateTime = DateTime.UtcNow;
        }

        /// <summary>
        /// 添加秒杀商品
        /// </summary>
        public void AddSeckillProduct(Guid productId, string seckillName, string seckillUrl,
                                     decimal seckillPrice, int seckillStock, int seckillLimit,
                                     string seckillDescription, SeckillType seckillType = SeckillType.Normal)
        {
            // 检查是否已存在相同商品的秒杀
            if (_seckillProducts.Any(sp => sp.ProductId == productId))
            {
                throw new InvalidOperationException($"商品ID '{productId}' 已存在于当前秒杀活动中");
            }

            var seckillProduct = new SeckillProduct(
                Id, // 使用当前秒杀活动的ID作为TimeId
                productId,
                seckillName,
                seckillUrl,
                seckillPrice,
                seckillStock,
                seckillLimit,
                seckillDescription,
                seckillType
            );

            _seckillProducts.Add(seckillProduct);
            UpdateTime = DateTime.UtcNow;
        }

        /// <summary>
        /// 移除秒杀商品
        /// </summary>
        public void RemoveSeckillProduct(Guid seckillProductId)
        {
            var product = _seckillProducts.FirstOrDefault(sp => sp.Id == seckillProductId);
            if (product != null)
            {
                _seckillProducts.Remove(product);
                UpdateTime = DateTime.UtcNow;
            }
        }

        /// <summary>
        /// 获取指定商品的秒杀商品
        /// </summary>
        public SeckillProduct? GetSeckillProduct(Guid productId)
        {
            return _seckillProducts.FirstOrDefault(sp => sp.ProductId == productId);
        }

        /// <summary>
        /// 检查秒杀活动是否正在进行中
        /// </summary>
        public bool IsActive()
        {
            if (TimeStatus != SeckillTimeStatus.Enabled)
                return false;

            var now = DateTime.UtcNow;
            var currentDate = DateOnly.FromDateTime(now);
            var currentTime = TimeOnly.FromDateTime(now);

            return SeckillDate == currentDate &&
                   currentTime >= SeckillStartTime &&
                   currentTime <= SeckillEndTime;
        }

        /// <summary>
        /// 检查秒杀活动是否即将开始
        /// </summary>
        public bool IsUpcoming()
        {
            if (TimeStatus != SeckillTimeStatus.Enabled)
                return false;

            var now = DateTime.UtcNow;
            var currentDate = DateOnly.FromDateTime(now);
            var currentTime = TimeOnly.FromDateTime(now);

            return SeckillDate >= currentDate &&
                   (SeckillDate > currentDate || SeckillStartTime > currentTime);
        }

        /// <summary>
        /// 检查秒杀活动是否已结束
        /// </summary>
        public bool IsExpired()
        {
            var now = DateTime.UtcNow;
            var currentDate = DateOnly.FromDateTime(now);
            var currentTime = TimeOnly.FromDateTime(now);

            return SeckillDate < currentDate ||
                   (SeckillDate == currentDate && SeckillEndTime < currentTime);
        }

        /// <summary>
        /// 验证秒杀活动创建时的业务规则
        /// </summary>
        private void ValidateCreation()
        {
            if (string.IsNullOrWhiteSpace(TimeTitleUrl))
                throw new ArgumentException("秒杀时间主题URL不能为空");

            if (SeckillStartTime >= SeckillEndTime)
                throw new ArgumentException("秒杀开始时间必须早于结束时间");

            if (SeckillDate < DateOnly.FromDateTime(DateTime.UtcNow))
                throw new ArgumentException("秒杀日期不能是过去日期");
        }

        /// <summary>
        /// 验证基本信息
        /// </summary>
        private void ValidateBasicInfo()
        {
            if (string.IsNullOrWhiteSpace(TimeTitleUrl))
                throw new ArgumentException("秒杀时间主题URL不能为空");

            if (SeckillStartTime >= SeckillEndTime)
                throw new ArgumentException("秒杀开始时间必须早于结束时间");
        }
    }
}
